package com.yycx.module.bus.provider.service.impl;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaDelete;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.DateUtils;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.provider.mapper.BusSfinanceDetailsMapper;
import com.yycx.module.bus.provider.service.*;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 厂家对账明细接口实现类
 *
 * @author flyme
 * @date 2021-02-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusSfinanceDetailsServiceImpl extends BaseServiceImpl<BusSfinanceDetailsMapper, BusSfinanceDetails> implements BusSfinanceDetailsService {

    @Autowired
    private BusSfinanceService busSfinanceService;

    @Resource
    private BusOrderDetailsService orderDetailsService;


    @Resource
    private BusSupplierService supplierService;

    @Resource
    private BusCustomService customService;

    @Resource
    private BusDrugsService drugsService;


    @Resource
    private BusSalemanService salemanService;

    @Resource
    private BusDeptService deptService;

    @Resource
    private BusOrderService orderService;


    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusSfinanceDetails bsd, EntityMap extra) {
        String orderNo = cs.getParams("orderNo");
        Long sfinanceId = cs.getLong("sfinanceId");
        ApiAssert.isNotEmpty("修正原订单号不能为空", orderNo);
        BusOrder order = orderService.getByProperty("orderNo", orderNo);
        ApiAssert.isNotEmpty("修正原订单不存在", order);
        bsd.setOrderId(order.getOrderId());
        BusDept dept = deptService.getById(order.getDeptId());
        bsd.setDeptName(dept.getDeptName());
        bsd.setSaleDate(DateUtils.formatDate(order.getSendDate()));
        bsd.setSfinanceId(sfinanceId);
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusSfinanceDetails> cq, BusSfinanceDetails bsd, EntityMap requestMap) {
        cq.orderByDesc("bsd.createTime");
        return ResultBody.ok();
    }

    @Override
    public List<BusSfinanceDetails> getShangQiList(BusSfinance benQiHjFinance) {
        List<BusSfinanceDetails> detailsList = new ArrayList<>();
        if (FlymeUtils.isNotEmpty(benQiHjFinance)) {
            //本期月份
            String financeMonth = benQiHjFinance.getFinanceMonth();
            //对账表月份第一天
            String lastFirstDay = financeMonth + "-01";
            Long supplierId = benQiHjFinance.getSupplierId();
            CriteriaQuery cq = new CriteriaQuery(BusOrderDetails.class);
            cq.lt("saleDate", lastFirstDay);
            cq.eq(true, "supplierId", supplierId);
            cq.ne(true, "budan", financeMonth);
            cq.eq(true, "orderDetailsState", CommonConstants.ENABLED);
            cq.orderByAsc("saleDate");
            List<BusOrderDetails> orderDetailsList = orderDetailsService.list(cq);
            detailsList = initBusSfinanceDetails(orderDetailsList, benQiHjFinance);
        }
        return detailsList;
    }

    /**
     * 初始化对账明细
     *
     * @param benQiHjFinance
     */
    @Override
    public List<BusSfinanceDetails> getBenQiHeJiList(BusSfinance benQiHjFinance) {
        if (FlymeUtils.isNotEmpty(benQiHjFinance)) {
            String financeMonth = benQiHjFinance.getFinanceMonth();
            Long supplierId = benQiHjFinance.getSupplierId();
            CriteriaQuery<BusOrderDetails> cq = new CriteriaQuery(BusOrderDetails.class);
            cq.and(e->e.likeRight("saleDate",financeMonth).or().likeRight("budan",financeMonth));
            cq.eq(true, "supplierId", supplierId);
            cq.eq(true, "orderDetailsState", CommonConstants.ENABLED);
            cq.orderByAsc("saleDate");
            //查询订单明细
            List<BusOrderDetails> orderDetailsList = orderDetailsService.list(cq);
            //转化为BusSfinanceDetails对象
            List<BusSfinanceDetails> detailsList = initBusSfinanceDetails2(orderDetailsList, benQiHjFinance);
            return detailsList;
        }
        return null;
    }

    /**
     * 计算本期明细
     *
     * @param orderDetailsList
     * @param benQiHjFinance
     * @return
     */
    private List<BusSfinanceDetails> initBusSfinanceDetails(List<BusOrderDetails> orderDetailsList, BusSfinance benQiHjFinance) {


        Long supplierId = benQiHjFinance.getSupplierId();
        List<BusSfinanceDetails> detailsList = new ArrayList<>();
        //本期月份最后一天
        String lastDay = DateUtils.format(DateUtils.getLastDayOfMonth(benQiHjFinance.getFinanceMonth() + "-01"));
        if (FlymeUtils.isNotEmpty(orderDetailsList)) {

            String financeMonth = benQiHjFinance.getFinanceMonth();
            for (BusOrderDetails orderDetails : orderDetailsList) {
                Long orderDetailsId = orderDetails.getOrderDetailsId();
                BusSfinanceDetails busFinanceDetails = new BusSfinanceDetails();
                busFinanceDetails.setSfinanceId(benQiHjFinance.getSfinanceId());
                busFinanceDetails.setOrderDetailsId(orderDetailsId);
                busFinanceDetails.setOrderId(orderDetails.getOrderId());
                Integer saleType = FlymeUtils.getInteger(orderDetails.getSaleType(), 0);
                BusOrder order = orderService.getById(orderDetails.getOrderId());
                BusDrugs drugs = drugsService.getById(orderDetails.getDrugsId());
                BusDept dept = deptService.getById(orderDetails.getDeptId());
                BusCustom custom = customService.getById(orderDetails.getCustomId());
                //供方应返金额
                BigDecimal supplierRettable = FlymeUtils.getBigDecimal(orderDetails.getSupplierRetable(), "0");

                //已返金额
                BigDecimal supplierRealAmount = FlymeUtils.getBigDecimal(orderDetails.getSupplierRealAmount(), "0");

                //高开税金
                BigDecimal supplierGapUpTaxesAmount = FlymeUtils.getBigDecimal(orderDetails.getSupplierGapUpTaxesAmount(), "0");

                //发货底价
                BigDecimal fahuoDjAmount = FlymeUtils.getBigDecimal(orderDetails.getCustomFloorAmount(), "0");

                //成本金额
                BigDecimal costAmount = FlymeUtils.getBigDecimal(orderDetails.getCostAmount(), "0");

                busFinanceDetails.setOrderNo(order.getOrderNo());
                busFinanceDetails.setDrugsName(drugs.getDrugsName());
                busFinanceDetails.setCustomName(custom.getCustomName());
                busFinanceDetails.setSaleNum(orderDetails.getSaleNum().toString());
                busFinanceDetails.setDrugsSpec(drugs.getDrugsSpec());
                if (FlymeUtils.isNotEmpty(orderDetails.getSaleDate())) {
                    busFinanceDetails.setSaleDate(DateUtils.formatDate(orderDetails.getSaleDate()));
                }
                busFinanceDetails.setDeptName(dept.getDeptName());
                busFinanceDetails.setSalePrice(orderDetails.getSalePrice());
                busFinanceDetails.setCostPrice(orderDetails.getCostPrice());
                BusSaleman saleman = salemanService.getById(orderDetails.getSaleManId());
                if(FlymeUtils.isNotEmpty(saleman)){
                    busFinanceDetails.setSaleManName(saleman.getSaleManName());
                }
                busFinanceDetails.setSaleAmount(FlymeUtils.getBigDecimal(orderDetails.getSaleAmount(), "0"));
                busFinanceDetails.setCostAmount(costAmount);
                busFinanceDetails.setSupplierRetable(supplierRettable);
                busFinanceDetails.setRemark(orderDetails.getRemark());
                busFinanceDetails.setSupplierRealDate(orderDetails.getSupplierRetDate());
                busFinanceDetails.setSupplierSettleRate(orderDetails.getSupplierSettleRate());
                busFinanceDetails.setRenkuanDate(orderDetails.getRenkuanDate());
                busFinanceDetails.setSupplierBondDate(orderDetails.getSupplierBondPayDate());
                //供货方高开税金
                busFinanceDetails.setSupplierGapUpTaxesAmount(supplierGapUpTaxesAmount);
                //与供方开票金额
                busFinanceDetails.setInvoicePaymentAmount(FlymeUtils.getBigDecimal(orderDetails.getInvoicePaymentAmount(), "0"));

                String supplierRetBondDate = orderDetails.getSupplierRetBondDate();
                if (FlymeUtils.isNotEmpty(supplierRetBondDate) && DateUtils.le(supplierRetBondDate, lastDay)) {
                    //退垫付金额
                    busFinanceDetails.setReturnSupplierBond(FlymeUtils.getBigDecimal(orderDetails.getReturnSupplierBond(), "0"));
                    //退垫付款日期
                    busFinanceDetails.setReturnSupplierBondDate(orderDetails.getSupplierRetBondDate());
                }
                detailsList.add(busFinanceDetails);


                String renkuanDate = orderDetails.getRenkuanDate();
                if (FlymeUtils.isNotEmpty(renkuanDate) && DateUtils.le(renkuanDate + "-01", lastDay)) {
                    //回款信息
                    busFinanceDetails.setReturnDate(orderDetails.getReturnDate());
                    busFinanceDetails.setReturnAmount(FlymeUtils.getBigDecimal(orderDetails.getReturnAmount(), "0"));
                }


                String supplierRetDate2 = orderDetails.getSupplierRetDate2();
                if (FlymeUtils.isNotEmpty(supplierRetDate2) && DateUtils.le(supplierRetDate2 + "-01", lastDay)) {
                    //返款信息
                    busFinanceDetails.setSupplierRealDate(orderDetails.getSupplierRetDate());
                    busFinanceDetails.setSupplierRealAmount(FlymeUtils.getBigDecimal(orderDetails.getSupplierRealAmount(), "0"));
                }
                String supplierBondPayDate = orderDetails.getSupplierBondPayDate();
                if (FlymeUtils.isNotEmpty(supplierBondPayDate) && DateUtils.le(supplierBondPayDate, lastDay)) {
                    //垫付信息
                    busFinanceDetails.setSupplierBondDate(orderDetails.getSupplierBondPayDate());
                    busFinanceDetails.setSupplierBondAmount(FlymeUtils.getBigDecimal(orderDetails.getSupplierPayBond(), "0"));
                }
            }
        }
        return detailsList;
    }

    /**
     * 计算本期明细
     *
     * @param orderDetailsList
     * @return
     */
    private List<BusSfinanceDetails> initBusSfinanceDetails2(List<BusOrderDetails> orderDetailsList, BusSfinance benQiHjFinance) {
        List<BusSfinanceDetails> detailsList = new ArrayList<>();

        if (FlymeUtils.isNotEmpty(orderDetailsList)) {
            //本期月份第一天
            String lastFirstDay = benQiHjFinance.getFinanceMonth() + "-01";
            //本期月份最后一天
            String lastDay = DateUtils.format(DateUtils.getLastDayOfMonth(lastFirstDay));
            //发货金额
            BigDecimal totalSaleAmount = new BigDecimal("0");
            //回款金额
            BigDecimal totalReturnAmount = new BigDecimal("0");
            BigDecimal debtAmountTotal = new BigDecimal("0");
            BigDecimal supplierRettableTotal = new BigDecimal("0");
            BigDecimal supplierRealAmountTotal = new BigDecimal("0");
            BigDecimal supplierAmountTotal = new BigDecimal("0");
            BigDecimal supplierGapUpTaxesAmountTotal = new BigDecimal("0");
            BigDecimal fahuoDjAmountTotal = new BigDecimal("0");
            BigDecimal supplierPayBondTotal = new BigDecimal("0");
            BigDecimal returnSupplierBondTotal = new BigDecimal("0");
            BigDecimal costAmountTotal = new BigDecimal("0");
            for (BusOrderDetails orderDetails : orderDetailsList) {
                String budan=FlymeUtils.getString(orderDetails.getBudan(),"0");
                Long orderDetailsId = orderDetails.getOrderDetailsId();
                BusSfinanceDetails busFinanceDetails = new BusSfinanceDetails();
                busFinanceDetails.setSfinanceId(benQiHjFinance.getSfinanceId());
                busFinanceDetails.setOrderDetailsId(orderDetailsId);
                busFinanceDetails.setOrderId(orderDetails.getOrderId());
                BusOrder order = orderService.getById(orderDetails.getOrderId());
                BusDrugs drugs = drugsService.getById(orderDetails.getDrugsId());
                BusDept dept = deptService.getById(orderDetails.getDeptId());
                BusSaleman saleman = salemanService.getById(orderDetails.getSaleManId());
                BusCustom custom = customService.getById(orderDetails.getCustomId());
                //供方应返金额
                BigDecimal supplierRettable = FlymeUtils.getBigDecimal(orderDetails.getSupplierRetable(), "0");
                supplierRettableTotal = supplierRettableTotal.add(supplierRettable);
                //已返金额
                BigDecimal supplierRealAmount = FlymeUtils.getBigDecimal(orderDetails.getSupplierRealAmount(), "0");
                String supplierRetDate2 = orderDetails.getSupplierRetDate2();
                if (FlymeUtils.isNotEmpty(supplierRetDate2)) {
                    //返款信息
                    busFinanceDetails.setSupplierRealDate(orderDetails.getSupplierRetDate());
                    if (supplierRetDate2.equals(benQiHjFinance.getFinanceMonth())||budan.equals(benQiHjFinance.getFinanceMonth())) {
                        //只统计本期
                        //累加本期返款
                        supplierRealAmountTotal = supplierRealAmountTotal.add(supplierRealAmount);
                        busFinanceDetails.setSupplierRealAmount(FlymeUtils.getBigDecimal(orderDetails.getSupplierRealAmount(), "0"));
                    }
                }

                //高开税金
                BigDecimal supplierGapUpTaxesAmount = FlymeUtils.getBigDecimal(orderDetails.getSupplierGapUpTaxesAmount(), "0");
                supplierGapUpTaxesAmountTotal = supplierGapUpTaxesAmountTotal.add(supplierGapUpTaxesAmount);
                //发货底价
                BigDecimal fahuoDjAmount = FlymeUtils.getBigDecimal(orderDetails.getCustomFloorAmount(), "0");
                fahuoDjAmountTotal = fahuoDjAmountTotal.add(fahuoDjAmount);
                //成本金额
                BigDecimal costAmount = FlymeUtils.getBigDecimal(orderDetails.getCostAmount(), "0");
                costAmountTotal = costAmountTotal.add(costAmount);
                busFinanceDetails.setOrderNo(order.getOrderNo());
                busFinanceDetails.setDrugsName(drugs.getDrugsName());
                busFinanceDetails.setSupplierBondType(order.getSupplierBondType());
                busFinanceDetails.setCustomName(custom.getCustomName());
                busFinanceDetails.setSaleNum(orderDetails.getSaleNum().toString());
                busFinanceDetails.setDrugsSpec(drugs.getDrugsSpec());
                busFinanceDetails.setRemark(orderDetails.getRemark());
                if (FlymeUtils.isNotEmpty(orderDetails.getSaleDate())) {
                    busFinanceDetails.setSaleDate(DateUtils.formatDate(orderDetails.getSaleDate()));
                }
                busFinanceDetails.setDeptName(dept.getDeptName());
                busFinanceDetails.setSalePrice(orderDetails.getSalePrice());
                busFinanceDetails.setCostPrice(orderDetails.getCostPrice());
                if(FlymeUtils.isNotEmpty(saleman)) {
                    busFinanceDetails.setSaleManName(saleman.getSaleManName());
                }
                busFinanceDetails.setSaleAmount(FlymeUtils.getBigDecimal(orderDetails.getSaleAmount(), "0"));
                busFinanceDetails.setCostAmount(costAmount);
                busFinanceDetails.setSupplierRetable(supplierRettable);

                busFinanceDetails.setSupplierSettleRate(orderDetails.getSupplierSettleRate());

                busFinanceDetails.setSupplierBondDate(orderDetails.getSupplierBondPayDate());
                //供货方高开税金
                busFinanceDetails.setSupplierGapUpTaxesAmount(supplierGapUpTaxesAmount);
                //与供方开票金额
                busFinanceDetails.setInvoicePaymentAmount(FlymeUtils.getBigDecimal(orderDetails.getInvoicePaymentAmount(), "0"));

                String returnSupplierBondDate = orderDetails.getSupplierRetBondDate();


                if (FlymeUtils.isNotEmpty(returnSupplierBondDate)) {

                    busFinanceDetails.setReturnSupplierBondDate(orderDetails.getSupplierRetBondDate());
                    if ((DateUtils.ge(returnSupplierBondDate, lastFirstDay) && DateUtils.ge(lastDay, returnSupplierBondDate))||budan
                    .equals(benQiHjFinance.getFinanceMonth())) {
                        //退垫付款日期
                        //只统计本期
                        //累加退垫付款
                        returnSupplierBondTotal = returnSupplierBondTotal.add(FlymeUtils.getBigDecimal(orderDetails.getReturnSupplierBond(), "0"));
                        //退垫付金额
                        busFinanceDetails.setReturnSupplierBond(FlymeUtils.getBigDecimal(orderDetails.getReturnSupplierBond(), "0"));
                    }
                }

                detailsList.add(busFinanceDetails);
                //累加销售金额
                totalSaleAmount = totalSaleAmount.add(FlymeUtils.getBigDecimal(orderDetails.getSaleAmount(), "0"));

                //回款信息

                //认款日期
                String renkuanDate = orderDetails.getRenkuanDate();
                String returnDate = orderDetails.getReturnDate();
                busFinanceDetails.setRenkuanDate(orderDetails.getRenkuanDate());
                if (FlymeUtils.isNotEmpty(renkuanDate)) {
                    busFinanceDetails.setReturnDate(returnDate);
                    if (renkuanDate.equals(benQiHjFinance.getFinanceMonth())||budan.equals(benQiHjFinance.getFinanceMonth())) {
                        //只统计本期
                        //累加回款金额
                        totalReturnAmount = totalReturnAmount.add(FlymeUtils.getBigDecimal(orderDetails.getReturnAmount(), "0"));
                        busFinanceDetails.setReturnAmount(FlymeUtils.getBigDecimal(orderDetails.getReturnAmount(), "0"));
                    }
                }

                String supplierBondPayDate = orderDetails.getSupplierBondPayDate();

                if (FlymeUtils.isNotEmpty(supplierBondPayDate)) {
                    busFinanceDetails.setSupplierBondDate(orderDetails.getSupplierBondPayDate());

                    if ((DateUtils.ge(supplierBondPayDate, lastFirstDay) && DateUtils.ge(lastDay, supplierBondPayDate))||budan.equals(benQiHjFinance.getFinanceMonth())) {
                        //只统计本期
                        //累加垫付款
                        supplierPayBondTotal = supplierPayBondTotal.add(FlymeUtils.getBigDecimal(orderDetails.getSupplierPayBond(), "0"));
                        //垫付信息

                        busFinanceDetails.setSupplierBondAmount(FlymeUtils.getBigDecimal(orderDetails.getSupplierPayBond(), "0"));
                    }
                }

            }
            //累加购方欠款(销售金额-回款金额)
            debtAmountTotal = totalSaleAmount.subtract(totalReturnAmount);
            //累计应收供货方返款
            supplierAmountTotal = supplierRettableTotal.subtract(supplierRealAmountTotal);
            //本期合计对象赋值
            benQiHjFinance.setSupplierRetableAmount(supplierRettableTotal);
            benQiHjFinance.setSupplierRealAmount(supplierRealAmountTotal);
            benQiHjFinance.setSupplierGapUpTaxesAmount(supplierGapUpTaxesAmountTotal);
            benQiHjFinance.setSupplierAmount(supplierAmountTotal);
            benQiHjFinance.setCostAmount(costAmountTotal);
            benQiHjFinance.setSupplierBondAmount(supplierPayBondTotal);
            benQiHjFinance.setFahuoDjAmount(fahuoDjAmountTotal);
            benQiHjFinance.setSaleAmount(totalSaleAmount);
            benQiHjFinance.setSupplierBondReturnAmount(returnSupplierBondTotal);
            benQiHjFinance.setReturnAmount(totalReturnAmount);
            benQiHjFinance.setDebtAmount(debtAmountTotal);
            benQiHjFinance.setImportData(CommonConstants.DISABLED);
        } else {
            benQiHjFinance.setSupplierAmount(new BigDecimal("0"));
            benQiHjFinance.setSupplierRealAmount(new BigDecimal("0"));
            benQiHjFinance.setSupplierBondReturnAmount(new BigDecimal("0"));
            benQiHjFinance.setSupplierBondAmount(new BigDecimal("0"));
            benQiHjFinance.setCostAmount(new BigDecimal("0"));
            benQiHjFinance.setDebtAmount(new BigDecimal("0"));
            benQiHjFinance.setReturnAmount(new BigDecimal("0"));
            benQiHjFinance.setFahuoDjAmount(new BigDecimal("0"));
            benQiHjFinance.setSupplierGapUpTaxesAmount(new BigDecimal("0"));
            benQiHjFinance.setSaleAmount(new BigDecimal("0"));
            benQiHjFinance.setSupplierRetableAmount(new BigDecimal("0"));

        }
        return detailsList;
    }
    @Override
    public List<BusSfinanceDetails> listBySFinanceId(Long sfinanceId) {
        CriteriaQuery cq = new CriteriaQuery(BusSfinanceDetails.class);
        cq.eq(true, "sfinanceId", sfinanceId);
        return list(cq);
    }
}
